package com.xh.bussiness.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.exam.service.IUserErrorQuestionService;
import com.xh.bussiness.system.bean.dto.TeacherBean;
import com.xh.bussiness.system.bean.request.TeacherRequest;
import com.xh.bussiness.system.model.Teacher;
import com.xh.bussiness.system.service.IStudentCallLogService;
import com.xh.bussiness.system.service.ITeacherService;
import com.xh.bussiness.teachbook.service.ITeachingBookService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.bean.XhExportHeaderBean;
import com.xh.core.bean.XhPage;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Pitt zhang
 * @since 2019-04-09
 */
@Controller
@Api(tags = "教师相关接口")
@RequestMapping("/system/teacher")
public class TeacherController extends BaseController {

    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private IUserErrorQuestionService userErrorQuestionService;
    @Autowired
    private ITeachingBookService teachingBookService;
    @Autowired
    private IStudentCallLogService studentCallLogService;

    /**
     * 跳转列表页面
     *
     * @return
     */
    @RequestMapping("/toList")
    public String toList() {
        return "admin/system/teacher/list";
    }


    /**
     * 分页数据查询
     *
     * @param page 分页对象
     * @param bean 查询条件Bean
     * @return
     */
    @RequestMapping("/queryPage")
    @ResponseBody
    public XhPage queryPage(XhPage page, TeacherRequest bean) {
        page = teacherService.queryTeacherPage(page, bean);
        return page;
    }

    /**
     * 导出全部
     *
     * @param bean
     * @return
     */
    @RequestMapping(value = "/exportAll", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult exportAll(TeacherRequest bean, HttpServletRequest request) {
        try {
            LinkedHashMap<String, XhExportHeaderBean> exportHeaderBeans = new LinkedHashMap<>();
            //exportHeaderBeans.put("username",new XhExportHeaderBean("用户名"));
            //exportHeaderBeans.put("deleted",new XhExportHeaderBean("是否删除",ImmutableMap.of(0,"否",1,"是")));
            //exportHeaderBeans.put("createTime",new XhExportHeaderBean("创建时间","yyyy-MM-dd HH:mm:ss"));

            String downloadUrl = teacherService.exportAll(request, exportHeaderBeans, bean, "queryTeacherPage");
            if (downloadUrl != null) {
                return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "", downloadUrl);
            } else {
                return new AjaxResult(AjaxResultConstant.Result.ERROR, "导出失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(AjaxResultConstant.Result.ERROR);
        }
    }

    /**
     * 前往维护页面
     *
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "admin/system/teacher/add";
    }

    /**
     * 前往维护页面
     *
     * @return
     */
    @RequestMapping("/toModify/{id}")
    public String toModify(@PathVariable String id) {
        return "admin/system/teacher/modify";
    }

    /**
     * 前往查看页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/toView/{id}")
    public String toView(@PathVariable String id) {
        System.out.println(JSONObject.toJSON(teacherService.getById(id)));
        return "admin/system/teacher/view";
    }

    /**
     * 新增和保存
     *
     * @param teacherBean 实体对象
     * @return
     */
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public AjaxResult saveOrUpdate(TeacherBean teacherBean) {
        if (teacherBean.getId() == null) {
            teacherService.insertObj(teacherBean);
        } else {
            teacherService.updateObj(teacherBean);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    @RequestMapping("/queryById/{id}")
    @ResponseBody
    public AjaxResult queryById(@PathVariable String id) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teacherService.getById(id));
    }


    @RequestMapping("/queryByUserId/{userId}")
    @ResponseBody
    public AjaxResult queryByUserId(@PathVariable String userId) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, teacherService.getTeacherByUserId(userId));
    }

    /**
     * 删除操作
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteById/{id}")
    @ResponseBody
    @Transactional
    public AjaxResult deleteById(@PathVariable String id) {
        teacherService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 批量删除操作
     *
     * @param ids
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    @Transactional
    public AjaxResult batchDelete(String[] ids) {
        teacherService.batchDelete(ids);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 教师端小程序基本信息查询
     *
     * @param teacherId 教师id
     * @return
     */
    @ApiOperation("教师端小程序基本信息查询")
    @RequestMapping("/queryBasicInfoForApplet")
    @ResponseBody
    public AjaxResult queryBasicInfoForApplet(String teacherId) {
        //电话回访数
        Integer telephoneReturnVisitCount = 0;
        //todo 电话回访
        QueryWrapper returnCallEq = new QueryWrapper();
        returnCallEq.eq("teacher_id", teacherId);
        telephoneReturnVisitCount = studentCallLogService.selectCount(returnCallEq);

        //错题数
        Integer errorQuestionCount = 0;
        Teacher teacher = teacherService.getById(teacherId);
        if (teacher != null) {
            QueryWrapper userErrorQuesEq = new QueryWrapper();
            userErrorQuesEq.eq("source_type", 2);
            userErrorQuesEq.eq("user_id", teacher.getUserId());
            errorQuestionCount = userErrorQuestionService.selectCount(userErrorQuesEq);
        }
        //教案数
        QueryWrapper tbEq = new QueryWrapper();
        tbEq.eq("teacher_id", teacherId);
        Integer teachingBookCount = teachingBookService.selectCount(tbEq);

        Map<String, Integer> retMap = new HashMap<>();
        retMap.put("telephoneReturnVisitCount", telephoneReturnVisitCount);
        retMap.put("errorQuestionCount", errorQuestionCount);
        retMap.put("teachingBookCount", teachingBookCount);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, retMap);
    }
}

